package com.ironman.h6b1gw.tlv;

import cn.hutool.core.util.HexUtil;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;

public class TLVEncoder {

    // 编码 TLV 结构（Type + Length + Value）
    public static byte[] encodeTLV(String typeHex, String valueHex) {
        byte[] type = HexUtil.decodeHex(typeHex);
        byte[] value = HexUtil.decodeHex(valueHex);
        byte[] length = encodeLength(value.length);
        ByteBuffer buffer = ByteBuffer.allocate(type.length + length.length + value.length);
        buffer.put(type);
        buffer.put(length);
        buffer.put(value);
        return buffer.array();
    }

    // BER 长度编码（支持单字节和长格式）
    private static byte[] encodeLength(int len) {
        if (len <= 0x7F) {
            return new byte[]{0, (byte) len};
        } else {
            int byteCount = (Integer.BYTES - Integer.numberOfLeadingZeros(len) + 7) / 8;
            byte[] bytes = new byte[byteCount + 1];
            bytes[0] = (byte) (0x80 | byteCount);
            for (int i = 0; i < byteCount; i++) {
                bytes[i + 1] = (byte) (len >> (8 * (byteCount - i - 1)));
            }
            return bytes;
        }
    }

    public static byte[] mergeBytes(byte[]... arrays) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        for (byte[] array : arrays) {
            if (array != null && array.length > 0) {
                outputStream.write(array, 0, array.length);
            }
        }
        return outputStream.toByteArray();
    }

    public static void main(String[] args) {
        // 一键分闸
        byte[] data1 = mergeBytes(encodeTLV("038A", "0000000000000001"), encodeTLV("0A02", "0800"));
        System.out.println(HexUtil.encodeHexStr(data1).toUpperCase());

        // 一键合闸
        byte[] data2 = mergeBytes(encodeTLV("0392", "0000000000000001"), encodeTLV("0A02", "0400"));
        System.out.println(HexUtil.encodeHexStr(data2).toUpperCase());
    }
}
